package com.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.util.DateUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.util.GetConfig;
import com.util.GsonUtil;
import com.util.WebChatUtil;

/**
 * 订单action
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseAction {

    /**
     * 获取全部订单
     * @param ordState=1000 全部    -1取消订单  0待支付  1待入住   2待评价
     * @return
     */

    @RequestMapping("/getAllOrderList")
    public ModelAndView getAllOrderList(HttpServletRequest request,String ordState,Integer pageIndex,Integer pageSize,String code){
        ModelAndView md = new ModelAndView("orderList");
        if(pageIndex==null){
            pageIndex=1;
        }
        if(pageSize==null){
            pageSize=200;
        }
        if(ordState==null||"".equals(ordState)){
        	ordState="1000";
        }
        String memberJson = getOrderListData(request,ordState,pageIndex,pageSize);
        if("gotoRegister".equals(memberJson)){
    		md=new ModelAndView("redirect:/home/gotoRegister");
    		md.addObject("namespase","order");
    		md.addObject("url","getAllOrderList");
    		return md;
        }
        if(memberJson!=null){
            Map<String,Object> map = GsonUtil.fromJson(memberJson,new TypeToken<Map<String, Object>>(){}.getType());
            Object tmp = map.get("dataList");
            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            if(!"".equals(tmp)){
                if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
                    list = (List<Map<String,Object>>)tmp;
                    if(list.size()>0){
                        for(int i =0;i<list.size();i++){
                            double ordStateStr = (Double)list.get(i).get("OrdState");
                            double roomNumStr = (Double)list.get(i).get("RoomNum");
                            double payTimeStr = (Double)list.get(i).get("PayTime");
                            Integer OrdState = (int)ordStateStr;
                            Integer RoomNum = (int)roomNumStr;
                            Integer PayTime = (int)payTimeStr;
                            list.get(i).put("OrdState",OrdState);
                            list.get(i).put("RoomNum",RoomNum);
                            list.get(i).put("PayTime",PayTime);
                            String totalSettlementStr = list.get(i).get("TotalSettlement").toString();
                            if(totalSettlementStr.indexOf(".0")>-1){
                                totalSettlementStr = totalSettlementStr.substring(0,totalSettlementStr.indexOf(".0"));
                                list.get(i).put("TotalSettlement",totalSettlementStr);
                            }
                            String accountMoneyStr = list.get(i).get("AccountMoney").toString();
                            if(accountMoneyStr.indexOf(".0")>-1){
                                accountMoneyStr = accountMoneyStr.substring(0,accountMoneyStr.indexOf(".0"));
                                list.get(i).put("AccountMoney",accountMoneyStr);
                            }
                        }
                    }
                }

                md.addObject("dataList",list);

            }
        }
        md.addObject("ordState",ordState);
        return md;
    }

    /**
     * ajax获取订单
     * @param ordState=1000
     * @return
     */

    @RequestMapping("/getOrderList")
    @ResponseBody
    public JSONObject getOrderList(HttpServletRequest request,String ordState,Integer pageIndex,Integer pageSize){
        JSONObject resultJson = new JSONObject();
        if(pageIndex==null){
            pageIndex=1;
        }
        if(pageSize==null){
            pageSize=999;
        }
        String memberJson = getOrderListData(request,ordState,pageIndex,pageSize);
        if(memberJson!=null){
            resultJson = JSONObject.fromObject(memberJson);
        }
        return resultJson;
    }

    /**
     * 根据订单号查询订单详情
     */
    @RequestMapping("/getOrderDetail")
    public ModelAndView getOrderDetail(HttpServletRequest request,String ordCode,String orderState){
        ModelAndView md = new ModelAndView("orderDetail");
        Map<String,Object> promap = new HashMap<String,Object>();
        if(ordCode==null){
            return md;
        }
        promap.put("OrdCode",ordCode);
        String memberJson=getHttpJson("Logistics/SAL/QueryOrdOfCode",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            md=new ModelAndView("redirect:/home/gotoRegister");
            return md;
        }
        if(memberJson!=null){
            Map<String,Object> map = GsonUtil.fromJson(memberJson,new TypeToken<Map<String, Object>>(){}.getType());

            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
                Object tmp = map.get("dataList");
                if(!"".equals(tmp)){
                    list = (List<Map<String,Object>>)tmp;
                    if(list.size()>0){
                        for(int i =0;i<list.size();i++){
                            double orderStatStr = (Double)list.get(i).get("OrdState");
                            double roomNumStr = (Double)list.get(i).get("RoomNum");
                            double delayedTotalNumStr = (Double)list.get(i).get("DelayedTotalNum");
                            double payTimeStr = (Double)list.get(i).get("PayTime");
                            Integer OrdState = (int)orderStatStr;
                            Integer RoomNum = (int)roomNumStr;
                            Integer DelayedTotalNum = (int)delayedTotalNumStr;
                            Integer PayTime = (int)payTimeStr;
                            list.get(i).put("OrdState",OrdState);
                            list.get(i).put("RoomNum",RoomNum);
                            list.get(i).put("DelayedTotalNum",DelayedTotalNum);
                            list.get(i).put("PayTime",PayTime);
                            String arrivalsDate = list.get(i).get("ArrivalsTime").toString();
                            String checkOutDate = list.get(i).get("CheckOutTime").toString();
                            list.get(i).put("ArrivalsTime", arrivalsDate.substring(0,arrivalsDate.indexOf(" ")));
                            list.get(i).put("CheckOutTime", checkOutDate.substring(0,arrivalsDate.indexOf(" ")));
                        }
                    }
                }
                md.addObject("dataList",list);
            }
            List<Map<String,Object>> roomList = (List<Map<String,Object>>)map.get("RoomList");
            md.addObject("RoomList",roomList);
            md.addObject("orderState",orderState);
//        	String ticket=(String) getHttpSession(request).getAttribute(tokenKey);
//        	if(ticket==null){
//        		ticket=WebChatUtil.getJsTicket();
//        		getHttpSession(request).setAttribute(tokenKey,ticket);
//        	}
        	String url = GetConfig.getString("base_url")+"order/getOrderDetail";
        	Map<String, String> wxMap = WebChatUtil.getJsapi(url);
        	md.addObject("wxMap",wxMap);
        }
        return md;
    }


    /**
     * 取消订单
     * @param ordCode
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public JSONObject cancelOrder(HttpServletRequest request,String ordCode){
        JSONObject resultJson = new JSONObject();
        if(ordCode==null){
            resultJson.put("stateID",3);
            resultJson.put("msgInfo","参数错误");
        }
        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("OrdCode",ordCode);
        String memberJson=getHttpJson("Logistics/SAL/CancelOrd",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            resultJson.put("stateID",4);
        }
        if(memberJson!=null){
            resultJson = JSONObject.fromObject(memberJson);
        }
        return resultJson;
    }

    /**
     * 删除订单
     * @param ordCode
     * @return
     */
    @RequestMapping("/delOrder")
    @ResponseBody
    public JSONObject delOrder(HttpServletRequest request,String ordCode){
        JSONObject resultJson = new JSONObject();
        if(ordCode==null){
            resultJson.put("stateID",3);
            resultJson.put("msgInfo","参数错误");
        }
        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("OrdCode",ordCode);
        String memberJson=getHttpJson("Logistics/SAL/DeleteOrd",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            resultJson.put("stateID",4);
        }
        if(memberJson!=null){
            resultJson = JSONObject.fromObject(memberJson);
        }
        return resultJson;
    }


    /**
     * 支付订单
     * @param ordCode
     * @return
     */
    @RequestMapping("/payOrder")
    @ResponseBody
    public JSONObject payOrder(HttpServletRequest request,String ordCode,Integer paymentType){
        JSONObject resultJson = new JSONObject();
        if(ordCode==null||paymentType==null){
            resultJson.put("stateID",3);
            resultJson.put("msgInfo","参数错误");
        }
        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("OrdCode",ordCode);
        promap.put("PaymentType",paymentType);
        String memberJson=getHttpJson("Logistics/SAL/PaymentOrd",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            resultJson.put("stateID",4);
        }
        if(memberJson!=null){
            resultJson = JSONObject.fromObject(memberJson);
        }
        return resultJson;
    }





    /**
     * 根据不同条件查询订单
     * @param OrdState:订单状态
     * @param PageIndex:当前页数
     * @param PageSize：每页条数
     * @return
     */
    private String getOrderListData(HttpServletRequest request,String OrdState,Integer PageIndex,Integer PageSize){
        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("OrdState",OrdState);
        promap.put("PageIndex",PageIndex);
        promap.put("PageSize",PageSize);
        String memberJson=getHttpJson("Logistics/SAL/QueryOrd",GsonUtil.toJson(promap),request,true);
        return memberJson;
    }
   /**-------------------------------评价---------------------------------------*/

    /**
     * 跳转添加评价
     * @param ordCode:订单id
     * @return
     */
    @RequestMapping("/gotoAddEvaluate")
    public ModelAndView gotoAddEvaluate(HttpServletRequest request,String ordCode,String hotelName,String memkey){
        ModelAndView md = new ModelAndView("addEvaluate");
        md.addObject("OrdCode",ordCode);
        md.addObject("HotelName",hotelName);
//    	String ticket=(String) getHttpSession(request).getAttribute(tokenKey);
//    	if(ticket==null){
//    		ticket=WebChatUtil.getJsTicket();
//    		getHttpSession(request).setAttribute(tokenKey,ticket);
//    	}
    	String url = GetConfig.getString("base_url")+"order/gotoAddEvaluate";
    	Map<String, String> map = WebChatUtil.getJsapi(url);
    	md.addObject("wxMap",map);
        return md;
    }
    /**
     * 添加评价
     *
     */
    @RequestMapping("/addEvaluate")
    @ResponseBody
    public JSONObject addEvaluate(HttpServletRequest request,String ordCode,Integer grade,String remarks,String serverId){
        JSONObject resultJson = new JSONObject();
        if(ordCode==null||grade==null||grade==0|remarks==null){
            resultJson.put("stateID",3);//状态等于3为参数错误
            resultJson.put("msgInfo","参数错误");
            return resultJson;
        }
        List<Map<String,String>> PicList=new ArrayList<Map<String,String>>();
        if(serverId!=null){
            String serverIds[] = serverId.split(",");
            for(String id:serverIds){
                if(id!=null&&!"".equals(id)){
                    Map<String,String> idMap=new HashMap<String,String>();
                    idMap.put("ServerId",id);
                    PicList.add(idMap);
                }
            }
        }

        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("OrdCode",ordCode);
        promap.put("Grade",grade);
        promap.put("Remarks",remarks);
        promap.put("PicList",PicList);
        String memberJson=getHttpJson("Logistics/SAL/HotelEvaluate",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            resultJson.put("stateID",4);
            resultJson.put("msgInfo","请登录");
        }
        if(memberJson!=null) {
            resultJson =JSONObject.fromObject(memberJson);
        }
        return resultJson;
    }

    /**
     * 获取此酒店评价列表 传酒店id
     * ----SAL/QueryHotelEvaluate
     */
    @RequestMapping("/getEvaluateList")
    public ModelAndView getEvaluateList(HttpServletRequest request,Integer pageIndex,Integer pageSize,String hotelKey,
    		String startDate,String endDate,String city,String cityName,String lng,String lat,String type ,String hotelName,String grade,String commentNum){
        ModelAndView md = new ModelAndView("hotelEvaluateList");
        if(pageIndex==null){
            pageIndex=1;
        }
        if(pageSize==null){
            pageSize=1000;
        }
        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("PageIndex",pageIndex);
        promap.put("PageSize",pageSize);
        promap.put("HotelKey",hotelKey);
        String memberJson=getHttpJson("Logistics/SAL/QueryHotelEvaluate",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            md=new ModelAndView("redirect:/home/gotoRegister");
            return md;
        }
        if(memberJson!=null) {
            Map<String, Object> map = GsonUtil.fromJson(memberJson, new TypeToken<Map<String, Object>>() {}.getType());
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if((Double)map.get("stateID")==0 && (Double)map.get("businessState")==0){
                Object tmp = map.get("dataList");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

                if (!"".equals(tmp)) {
                    list = (List<Map<String, Object>>) tmp;
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            double gradeStr = (Double) list.get(i).get("Grade");
                            Integer Grade = (int) gradeStr;
                            list.get(i).put("Grade", Grade);
                            String createDataStr = list.get(i).get("CreateDate").toString();
                            createDataStr = createDataStr.substring(0,createDataStr.indexOf(" "));
                            list.get(i).put("CreateDate", createDataStr);

                        }
                    }
                }
            }
            md.addObject("dataList", list);
            md.addObject("size", list.size());
        }
        md.addObject("hotelKey", hotelKey);
		md.addObject("startDate",startDate);
		md.addObject("endDate",endDate);
    	md.addObject("cityName",cityName);
    	md.addObject("city",city);
    	md.addObject("lng",lng);
    	md.addObject("lat",lat);
    	md.addObject("type",type);
    	md.addObject("hotelName",hotelName);
    	md.addObject("grade",grade);
    	md.addObject("commentNum",commentNum);
        return md;
    }


    /**
     * 删除评价
     *
     */
    @RequestMapping("/delEvaluate")
    @ResponseBody
    public JSONObject delEvaluate(Integer id,HttpServletRequest request){
        JSONObject resultJson = new JSONObject();
        if(id==null){
            resultJson.put("stateID",3);//状态等于3为参数错误
            resultJson.put("msgInfo","参数错误");
            return resultJson;
        }
        Map<String,Object> promap = new HashMap<String,Object>();
        promap.put("ID",id);
        String memberJson=getHttpJson("Logistics/SAL/DelMemEvaluate",GsonUtil.toJson(promap),request,true);
        if("gotoRegister".equals(memberJson)){
            resultJson.put("stateID",4);
            resultJson.put("msgInfo","请登录");
        }
        if(memberJson!=null) {
            resultJson =JSONObject.fromObject(memberJson);
        }
        return resultJson;
    }

}
